<?php

use app\modules\Admin\models\goodspackageModel;
use app\modules\Admin\models\pickgoodscardModel;
use Illuminate\Database\Capsule\Manager as DB;

#[商品套餐管理]
class GoodspackageController extends AcommonController
{
    public function init() {
        $this->model = new goodsModel();
        $this->table = 'goods';
        $this->primaryKey = 'id';
        parent::init();
    }

    #[商品套餐列表]
    public function indexAction($returnData = FALSE)
    {
        if ($this->isPost()) {
            $this->model = $this->model->where(function ($query){
                $query->whereNull('deleted_at')->orWhereDate('deleted_at', '<=', '0000-00-00');
            })->where('is_package', 1);
            $keywords = $this->get('keywords');
            if (!empty($keywords)) {
                array_push($this->search, ['id', '=', $keywords]);
                array_push($this->search, ['title', 'like', "%{$keywords}%", 'or']);
            }
            $dataset = parent::indexAction(true);
            foreach ($dataset['rows'] as $k => &$v) {
                $v['stock'] = goodsskupriceModel::query()->where('goods_id', $v['id'])->value('stock');
            }
            json($dataset);
        } else {
            parent::indexAction();
        }
    }

    #[添加商品套餐]
    public function addAction()
    {
        if (!$this->isPost()) {
            $skuPrice = $this->getTableColumn('goods_sku_price');
            $this->_view->assign('skuPrice', json_encode([$skuPrice]));
            $this->_view->assign('goodsService', goodsserviceModel::all()->toJson());
            $this->_view->assign('categoryTree', $this->categoryTree()->toJson());
            $this->_view->assign('expressTemp', DB::table('dispatch')->where('type', 'express')->get()->toJson());
            $this->_view->assign('storeTemp', DB::table('dispatch')->where('type', 'store')->get()->toJson());
            $this->_view->assign('selfetchTemp', DB::table('dispatch')->where('type', 'selfetch')->get()->toJson());
            $this->_view->assign('autosendTemp', DB::table('dispatch')->where('type', 'autosend')->get()->toJson());
            $TableColumn = $this->getTableColumn($this->table);
            $dataset = array_merge($TableColumn,['innerCards'=>[], 'innerGoods'=>[], 'packageType' => 0]);
            $this->_view->assign('dataset', json_encode($dataset));
            $this->_view->display( strtolower($this->controller) . '/edit.html');
        } else {
            $rows               = $this->postData['params'];
            $rows['created_at'] = timestamp();
            $rows['is_package'] = 1;
            $rows['is_sku'] = 0;
            $packageType = $rows['packageType'];
            $innerGoods = '';
            $innerCards = '';
            if($packageType == 0 || $packageType == 2){
                $innerGoods = $rows['innerGoods']?json_encode($rows['innerGoods'], JSON_UNESCAPED_UNICODE):'';
            }
            if($packageType == 1 || $packageType == 2){
                $innerCards = $rows['innerCards']?json_encode($rows['innerCards'], JSON_UNESCAPED_UNICODE):'';
            }
            unset($rows['updated_at']);
            unset($rows['deleted_at']);
            $this->cleanColumn($rows);
            try {
                DB::beginTransaction();
                $goods_id = $this->model->insertGetId($rows);
                if ($rows['is_sku'] == 0) {
                    $skuPriceRow = [
                        'goods_id'      => $goods_id,
                        'image'         => $rows['image'],
                        'stock'         => $this->postData['skuPrice'][0]['stock'],
                        'stock_warning' => $this->postData['skuPrice'][0]['stock_warning'],
                        'sn'            => $this->postData['skuPrice'][0]['sn'],
                        'sales'         => $rows['sales'],
                        'weight'        => $rows['weight'],
                        'price'         => $rows['price'],
                        'cost_price'    => $rows['cost_price'],
                        'score'         => $rows['score'],
                        'status'        => $rows['status'],
                        'created_at'    => date('Y-m-d H:i:s'),
                    ];
                    goodsskupriceModel::insert($skuPriceRow);
                }
                if($rows['is_package'] > 0){
                    goodspackageModel::insert([
                        'goods_id'      => $goods_id,
                        'relation_goods_info' => $innerGoods,
                        'card_info' => $innerCards,
                    ]);
                }
                DB::commit();
                $result = [
                    'ret' => 0,
                    'msg' => '新增商品套餐操作成功',
                ];
            } catch (\Exception $e) {
                DB::rollBack();
                $result = [
                    'ret' => 30001,
                    'msg' => $e->getMessage(),
                ];
            }
            json(array_merge($result, ['rows' => $rows, 'innerCards' => $innerCards, 'innerGoods' => $innerGoods]));
        }
    }

    #[编辑商品套餐]
    public function editAction()
    {
        if (!$this->isPost()) {
            $id      = $this->get('id');
            $skuPrice = goodsskupriceModel::where('goods_id', $id)->get();
            $this->_view->assign('skuPrice', $skuPrice->toJson());
            $this->_view->assign('goodsService', goodsserviceModel::all()->toJson());
            $this->_view->assign('categoryTree', $this->categoryTree()->toJson());
            $this->_view->assign('expressTemp', DB::table('dispatch')->where('type', 'express')->get()->toJson());
            $this->_view->assign('storeTemp', DB::table('dispatch')->where('type', 'store')->get()->toJson());
            $this->_view->assign('selfetchTemp', DB::table('dispatch')->where('type', 'selfetch')->get()->toJson());
            $this->_view->assign('autosendTemp', DB::table('dispatch')->where('type', 'autosend')->get()->toJson());
            $query = $this->model->with('getGoodsPackageInfo');
            $id	= $this->get($this->primaryKey, 0);
            if($query->where($this->primaryKey,'=',$id)->doesntExist()){
                throw new Exception("记录不存在");
            }
            $query = $query->where($this->primaryKey,'=',$id)->first();
            if(!empty($this->appends)){
                foreach ($this->appends as $append){
                    $query = $query->append($append);
                }
            }
            $dataset = $query->toArray();
            $dataset = array_merge($dataset,['innerCards'=>[], 'innerGoods'=>[], 'packageType' => 0, 'goods_package_id' => 0]);
            $this->_view->assign('dataset', json_encode($dataset, JSON_UNESCAPED_UNICODE));
            $this->_view->display( strtolower($this->controller) . '/edit.html');
        } else {
            $rows               = $this->postData['params'];
            $rows['updated_at'] = date('Y-m-d H:i:s');
            $goods_package_id = $rows['goods_package_id'];
            $innerGoods = '';
            $innerCards = '';
            if($rows['packageType'] == 0 || $rows['packageType'] == 2){
                $innerGoods = $rows['innerGoods']?json_encode($rows['innerGoods'], JSON_UNESCAPED_UNICODE):'';
            }
            if($rows['packageType'] == 1 || $rows['packageType'] == 2){
                $innerCards = $rows['innerCards']?json_encode($rows['innerCards'], JSON_UNESCAPED_UNICODE):'';
            }
            $rows['updated_at'] = timestamp();
            unset($rows['created_at']);
            unset($rows['deleted_at']);
            $this->cleanColumn($rows);
            try {
                DB::beginTransaction();
                $goods_id = $rows['id'];
                $this->model->where('id', $rows['id'])->update($rows);
                if ($rows['is_sku'] == 0) {
                    $skuPriceRow = [
                        'goods_id'      => $goods_id,
                        'image'         => $rows['image'],
                        'stock'         => $this->postData['skuPrice'][0]['stock'],
                        'stock_warning' => $this->postData['skuPrice'][0]['stock_warning'],
                        'sn'            => $this->postData['skuPrice'][0]['sn'],
                        'sales'         => $this->postData['skuPrice'][0]['sales'] ?: 0,
                        'weight'        => $this->postData['skuPrice'][0]['weight'] ?: 0,
                        'price'         => $this->postData['skuPrice'][0]['price'],
                        'cost_price'    => $this->postData['skuPrice'][0]['cost_price'],
                        'score'         => $this->postData['skuPrice'][0]['score'],
                        'status'        => $this->postData['skuPrice'][0]['status'],
                        'updated_at'    => date('Y-m-d H:i:s'),
                    ];
                    goodsskupriceModel::where('id', $this->postData['skuPrice'][0]['id'])->update($skuPriceRow);
                }
                if($rows['is_package'] > 0){
                    goodspackageModel::query()->where('id', $goods_package_id)->update([
                        'relation_goods_info' => $innerGoods,
                        'card_info' => $innerCards,
                    ]);
                }
                DB::commit();
                $result = [
                    'ret' => 0,
                    'msg' => '操作成功',
                ];
            } catch (\Exception $e) {
                DB::rollBack();
                $result = [
                    'ret' => 30002,
                    'msg' => $e->getMessage(),
                ];
            }
            json($result);
        }
    }

    #[删除商品套餐]
    public function deleteAction()
    {
        parent::deleteAction(); // TODO: Change the autogenerated stub
    }

    #[上架商品套餐]
    public function upAction()
    {
        $id = $this->get('id');
        goodsModel::where('id', $id)->update(['status'=>'up']);
        ret(0, '上架套餐成功');
    }

    #[下架商品套餐]
    public function downAction()
    {
        $id = $this->get('id');
        goodsModel::where('id', $id)->update(['status'=>'down']);
        ret(0, '下架套餐成功');
    }

    #[回收商品套餐]
    public function recycleAction()
    {
        do {
            $id = $this->get($this->primaryKey);
            if (empty($id)) {
                $result = [
                    'ret' => 40001,
                    'msg' => '参数为空',
                ];
                break;
            }
            if (DB::table($this->table)->where($this->primaryKey, '=', $id)->doesntExist()) {
                $result = [
                    'ret' => 40002,
                    'msg' => '记录不存在',
                ];
                break;
            }
            try {
                DB::table('goods')
                    ->where($this->primaryKey, '=', $id)
                    ->update(['deleted_at'=>date('Y-m-d H:i:s')]);
                $result = [
                    'ret' => 0,
                    'msg' => '操作成功',
                ];
            } catch (\Exception $e) {
                $result = [
                    'ret' => 30002,
                    'msg' => $e->getMessage(),
                ];
            }
        } while (FALSE);
        json($result);
    }

    #[获取待选择商品列表]
    public function getgoodslistAction()
    {
        if($this->isPost()){
            $query = goodsModel::query()->where('status', 'up')
                ->where('is_package', 0)->where(function ($query){
                $query->whereNull('deleted_at')->orWhereDate('deleted_at', '<=', '0000-00-00');
            });
            $keywords = $this->postData['keywords'];
            if (!empty($keywords)) {
                $query = $query->Where(function ($orwQuery) use($keywords){
                    $orwQuery->where('title', 'like',  "%{$keywords}%")
                        ->orWhere('id', $keywords);
                });
            }
            $total = $query->count();
            $query = $query->orderBy('id', 'DESC');
            $page = $this->get('page')?:1;
            $limit = $this->get('rows', 10);
            $offset = ($page - 1) * $limit;
            $query = $query->offset($offset)->limit($limit);
            $rows = $query->select(['id', 'image', 'title', 'is_sku', 'price', 'created_at'])
                ->get()->makeHidden(['dispatch_type_arr', 'parent_category_id']);
            if($rows){
                foreach ($rows as &$row){
                    $row->stock =  goodsskupriceModel::select(DB::raw('sum(stock) as allstock'))->where('goods_id', $row->id)->value('allstock');
                }
            }
            json(['total' => $total, 'rows' => $rows]);
        }else{
            $this->_view->display( strtolower($this->controller) . '/getgoodslist.html');
        }
    }

    #[获取待选择提货卡列表]
    public function getpickgoodscardlistAction()
    {
        if($this->isPost()){
            $query = pickgoodscardModel::query()->where(function ($validQuery){
                $validQuery->whereDate('validtime_end', '>=', timestamp())
                    ->orWhereNull('validtime_end');
            })->whereDate('gettime_end', '>=', timestamp())->where(function ($query){
                $query->whereNull('deleted_at')->orWhereDate('deleted_at', '<=', '0000-00-00');
            });
            $keywords = $this->postData['keywords'];
            if (!empty($keywords)) {
                $query = $query->Where(function ($orwQuery) use($keywords){
                    $orwQuery->where('name', 'like',  "%{$keywords}%")
                        ->orWhere('id', $keywords);
                });
            }
            $total = $query->count();
            $query = $query->orderBy('id', 'DESC');
            $page = $this->get('page')?:1;
            $limit = $this->get('rows', 10);
            $offset = ($page - 1) * $limit;
            $query = $query->offset($offset)->limit($limit);
            $rows = $query->select(['id', 'name', 'amount', 'type', 'created_at'])
                ->get()->makeHidden(['goods_ids_array']);
            json(['total' => $total, 'rows' => $rows]);
        }else{
            $this->_view->display( strtolower($this->controller) . '/getgoodscardlist.html');
        }
    }

    #[递归获取商品目录树]
    private function categoryTree(&$item = null)
    {
        $children = categoryModel::where('pid', $item->id ?? 0)->select('id', 'name as text')->orderBy('weigh', 'DESC')->orderBy('id', 'ASC')->get();
        if ($children->isNotEmpty()) {
            $item && $item->children = $children;
            foreach ($children as $v) {
                $v->name = htmlentities($v->name);
                $this->categoryTree($v);
            }
        }
        return $children;
    }
}